package main

import (
//		"io/ioutil"
		"fmt"
		"encoding/json"
		"sync"
		"strings"
		"time"
	   )

type HuobiMarkets struct{
	Market []string
}

type HuobiSymbolNode struct{
	Basecurrency string `json:"base-currency"`
	Quotecurrency string  `json:"quote-currency"`
	Tradepriceprecision string `json:"trade-price-precision"`
	Tradeamountprecision string `json:"trade-amount-precision"`
	Teradetotalprecision string `json:"trade-total-precision"`
	Feeprecision string  `json:"fee-precision"`
	Weight string  `json:"weight"`
	Tradeenable string  `json:"trade-enable"`
	Symbolpartition string  `json:"symbol-partition"`
	Delist bool  `json:"delist"`
	Symbol string `json:"symbol"`
	Symbolname string `json:"symbol-name"`
	Tradeenabled bool `json:"trade-enabled"`
}
type HuobiSymbols struct{
	Status string
	Data  []HuobiSymbolNode
}

var (
		configFile_huobi = "config/huobi.json"
	)

func HuobiMarketsToRedis(inWg *sync.WaitGroup) error{
	defer inWg.Done()

		//var markets HuobiMarkets

		t := time.Now()

	val, err := client.Get("HuobiMarketList").Result()
	if err != nil{
		fmt.Printf("HuobiMarketsToRedis() Error: %s\n", err)
		return err
	}
	var huobisymbols HuobiSymbols
	err = json.Unmarshal([]byte(val), &huobisymbols)
	if err != nil{
	        fmt.Printf("Huobi parse symbols Error: %s\n", err)
		    return err
    }


		  var wg sync.WaitGroup

			  //for v := range markets.Market{
			  for v := range huobisymbols.Data{
				  wg.Add(1)
					  // fmt.Printf("HuobiMarketToRedis(%s) begin.\n", markets.Market[v])
					  var s []string;
					  s = append(s,huobisymbols.Data[v].Basecurrency);
					  s = append(s,huobisymbols.Data[v].Quotecurrency);
					  go HuobiMarketToRedis(strings.Join(s,"_"), &wg)
					  //go HuobiMarketToRedis(markets.Market[v], &wg)
			  }

		  wg.Wait()

			  fmt.Printf("HuobiMarketsToRedis duration: %s\n", time.Now().Sub(t))

			  return nil
}

func HuobiMarketToRedis(name string, wg *sync.WaitGroup){
	defer wg.Done()

		//url := "https://api.huobi.pro/market/detail/merged?symbol=" + strings.ToLower(name)
		url := "https://api.huobi.pro/market/detail/merged?symbol=" + strings.Replace(name, "_", "", 1)
		//fmt.Printf("url=%s\n",url);
		body := httpGet(url)
		key := "huobi_" + name + "_Latest"

		err := client.Set(key, body, 0).Err()
		if err != nil {
			fmt.Printf("Error: %s\n", err)
		}else{
			// fmt.Printf("Success write: %s\n", key)
		}

}

func PullHuobiMarkets(wg *sync.WaitGroup){
	defer wg.Done()

		url := "https://api.huobi.pro/v1/settings/symbols"

		body := httpGet(url)

		var huobisymbol HuobiSymbols

		err := json.Unmarshal(body, &huobisymbol)
		if err != nil{
			fmt.Printf("PullHuobiMarkets() Error: %s\n", err)
		}

	value, err := json.Marshal(huobisymbol)
		key := "HuobiMarketList"

		err = client.Set(key, body, 0).Err()
		if err != nil {
			fmt.Printf("Key: %s,%s Error: %s\n", key,value, err)
		}
}
